import { create } from 'zustand'
import { cFetch } from '@/lib/Http'
export type ItemDataStore = {
  items: Item[]
  hasMore: boolean
  page: number
}
export type ItemType = 'curMonthStore' | 'lastMonthStore' | 'curYearStore' | 'customStore'
type FetchParam = {
  target: ItemType,
  firstPage: boolean,
  startDate?: string,
  endDate?: string
}
export type ItemStore = {
  curMonthStore: ItemDataStore,
  lastMonthStore: ItemDataStore,
  curYearStore: ItemDataStore,
  customStore: ItemDataStore,
  _fetch: (params:FetchParam) => void
  fetchMore: (target: ItemType, startDate?: string, endDate?: string) => void
  fetchFirstPage: (target: ItemType, startDate?: string, endDate?: string) => void
}
export const useItemStore = create<ItemStore>((set, get) => ({
  curMonthStore: {
    items: [],
    hasMore: false,
    page: 1,
  },
  lastMonthStore: {
    items: [],
    hasMore: false,
    page: 1,
  },
  curYearStore: {
    items: [],
    hasMore: false,
    page: 1,
  },
  customStore: {
    items: [],
    hasMore: false,
    page: 1,
  },
  // 定义 _fetch 函数
  _fetch: async ({ target, firstPage, startDate, endDate }:FetchParam) => {
    if (!startDate || !endDate) return
    const page = get()[target].page
    const response = await cFetch.get<Resources<Item>>('/item/list', {
      happened_after: startDate,
      happened_before: endDate,
      page
    })
    const { pager, resources } = response
    set((state) => {
      const update = firstPage ? resources : state[target].items.concat(resources)
      return {
        [target]: {
          ...state[target],
          items: update,
          hasMore: (pager.page - 1) * pager.per_page + resources.length < pager.count,
          page: state[target].page + 1,
        },
      }
    })
  },
  // 加载更多数据
  fetchMore: (target, startDate, endDate) => {
    get()._fetch({ target, firstPage: false, startDate, endDate })
  },
  // 加载第一页数据
  fetchFirstPage: (target, startDate, endDate) => {
    set((state:ItemStore) => ({
      [target]: { ...state[target], page: 1 },
    }))
    get()._fetch({ target, firstPage: true, startDate, endDate })
  },
}))
